<template>
  <el-dialog
    title="控制"
    v-model="state.show"
    width="550px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-form ref="formRef" label-width="60px">
      <el-form-item label="开关" prop="sw">
        <el-button icon="Select" type="primary" round plain @click="handleTurnOn()">开</el-button>
        <el-button icon="CloseBold" type="primary" round plain @click="handleTurnOff()">关</el-button>
      </el-form-item>
      <el-form-item label="调光" prop="sl">
        <el-slider v-model="state.sl" :max="100" :min="0" @change="percentageChange()" />
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script lang="ts" setup>
import { groupPropertySet } from '../api/devices.api'
// 引入公共方法获取设备属性
import { getDeviceProperties } from '@/utils/deviceUtils'

const state = reactive({
  show: false,
  row: {} as any,
  sw: 0,
  sl: 0,
  swName: '',
  slName: '',
})

const openDialog = (row: any) => {
  state.show = true
  state.row = row
  state.sl = 0
  
  const { swName, slName } = getDeviceProperties(row.product.productKey)
  state.swName = swName
  state.slName = slName
}

// 打开开关
const handleTurnOn = async () => {
  state.sw = 1
  await switchChange()
}

// 关闭开关
const handleTurnOff = async () => {
  state.sw = 0
  await switchChange()
}

// 开关按钮
const switchChange = async () => {
  const args = {}
  args[state.swName] = state.sw
  groupPropertySet({
    groupId: state.row.id,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '开关成功',
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 调光按钮
const percentageChange = async () => {
  const args = {}
  args[state.slName] = state.sl
  groupPropertySet({
    groupId: state.row.id,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '调光成功',
      })
    } else {
      ElMessage.error(res.message)
    }
  })
}

defineExpose({
  openDialog,
})
</script>
<style lang="scss" scoped>
.el-slider {
  padding: 10px 20px 10px 10px;
}
</style>